using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using UwinEducation.Application.Common.Interfaces.Orders;
using UwinEducation.Application.Dtos.Orders;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Shared.Exceptions;
using UwinEducation.Shared.Models;

namespace UwinEducation.Application.Services.Orders
{
    /// <summary>
    /// 订单折扣服务实现
    /// </summary>
    public class OrderDiscountService : IOrderDiscountService
    {
        private readonly IOrderDiscountRepository _orderDiscountRepository;
        private readonly IOrderRepository _orderRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="orderDiscountRepository">订单折扣仓储</param>
        /// <param name="orderRepository">订单仓储</param>
        /// <param name="mapper">映射器</param>
        public OrderDiscountService(
            IOrderDiscountRepository orderDiscountRepository,
            IOrderRepository orderRepository,
            IMapper mapper)
        {
            _orderDiscountRepository = orderDiscountRepository;
            _orderRepository = orderRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 根据ID获取订单折扣
        /// </summary>
        /// <param name="id">折扣ID</param>
        /// <returns>订单折扣DTO</returns>
        public async Task<OrderDiscountDto> GetByIdAsync(Guid id)
        {
            var discount = await _orderDiscountRepository.GetByIdAsync(id);
            if (discount == null)
            {
                throw new ArgumentException($"未找到ID为{id}的订单折扣");
            }

            return _mapper.Map<OrderDiscountDto>(discount);
        }

        /// <summary>
        /// 根据订单ID获取所有折扣
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>订单折扣DTO列表</returns>
        public async Task<List<OrderDiscountDto>> GetByOrderIdAsync(Guid orderId)
        {
            var discounts = await _orderDiscountRepository.GetByOrderIdAsync(orderId);
            return _mapper.Map<List<OrderDiscountDto>>(discounts);
        }

        /// <summary>
        /// 获取分页的订单折扣列表
        /// </summary>
        /// <param name="pageRequest">分页请求参数</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResult<OrderDiscountDto>> GetPagedListAsync(OrderDiscountPageRequest pageRequest)
        {
            // 查询分页数据
            var result = await _orderDiscountRepository.GetPagedAsync(pageRequest);

            // 将实体转换为DTO
            var dtoItems = _mapper.Map<List<OrderDiscountDto>>(result.Items);

            // 构建并返回分页结果
            return new PagedResult<OrderDiscountDto>
            {
                Items = dtoItems,
                Total = result.Total
            };
        }

        /// <summary>
        /// 创建订单折扣
        /// </summary>
        /// <param name="createDto">创建订单折扣DTO</param>
        /// <returns>创建的订单折扣DTO</returns>
        public async Task<OrderDiscountDto> CreateAsync(CreateOrderDiscountDto createDto)
        {
            // 检查订单是否存在
            var order = await _orderRepository.GetByIdAsync(createDto.OrderId);
            if (order == null)
            {
                throw new ArgumentException($"未找到ID为{createDto.OrderId}的订单");
            }

            // 创建订单折扣实体
            var discount = _mapper.Map<OrderDiscount>(createDto);
            discount.Id = Guid.NewGuid();
            discount.CreatedAt = DateTime.Now;

            // 保存到数据库
            await _orderDiscountRepository.AddAsync(discount);

            return _mapper.Map<OrderDiscountDto>(discount);
        }

        /// <summary>
        /// 批量创建订单折扣
        /// </summary>
        /// <param name="createDtos">创建订单折扣DTO列表</param>
        /// <returns>创建的订单折扣DTO列表</returns>
        public async Task<List<OrderDiscountDto>> CreateRangeAsync(List<CreateOrderDiscountDto> createDtos)
        {
            //if (createDtos == null || !createDtos.Any())
            //{
            //    return new List<OrderDiscountDto>();
            //}

            //// 获取所有涉及的订单ID
            //var orderIds = createDtos.Select(d => d.OrderId).Distinct().ToList();

            //// 检查所有订单是否存在
            //var orders = await _orderRepository.GetByIdsAsync(orderIds);
            //var existingOrderIds = orders.Select(o => o.Id).ToList();

            //// 找出不存在的订单ID
            //var nonExistingOrderIds = orderIds.Except(existingOrderIds).ToList();
            //if (nonExistingOrderIds.Any())
            //{
            //    throw new ArgumentException($"未找到以下ID的订单：{string.Join(", ", nonExistingOrderIds)}");
            //}

            //// 创建订单折扣实体
            //var discounts = createDtos.Select(dto =>
            //{
            //    var discount = _mapper.Map<OrderDiscount>(dto);
            //    discount.Id = Guid.NewGuid();
            //    discount.CreatedAt = DateTime.Now;
            //    return discount;
            //}).ToList();

            //// 保存到数据库
            //await _orderDiscountRepository.AddRangeAsync(discounts);

            //return _mapper.Map<List<OrderDiscountDto>>(discounts);

            return null;
        }

        /// <summary>
        /// 更新订单折扣
        /// </summary>
        /// <param name="updateDto">更新订单折扣DTO</param>
        /// <returns>更新后的订单折扣DTO</returns>
        public async Task<OrderDiscountDto> UpdateAsync(UpdateOrderDiscountDto updateDto)
        {
            // 检查折扣是否存在
            var discount = await _orderDiscountRepository.GetByIdAsync(updateDto.Id);
            if (discount == null)
            {
                throw new ArgumentException($"未找到ID为{updateDto.Id}的订单折扣");
            }

            // 更新折扣信息
            discount.DiscountAmount = updateDto.DiscountAmount;
            discount.Description = updateDto.Description;

            // 保存到数据库
            await _orderDiscountRepository.UpdateAsync(discount);

            return _mapper.Map<OrderDiscountDto>(discount);
        }

        /// <summary>
        /// 删除订单折扣
        /// </summary>
        /// <param name="id">折扣ID</param>
        /// <returns>操作结果</returns>
        public async Task DeleteAsync(Guid id)
        {
            // 检查折扣是否存在
            var discount = await _orderDiscountRepository.GetByIdAsync(id);
            if (discount == null)
            {
                throw new ArgumentException($"未找到ID为{id}的订单折扣");
            }

            // 删除折扣
            await _orderDiscountRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 批量删除订单折扣
        /// </summary>
        /// <param name="ids">折扣ID列表</param>
        /// <returns>操作结果</returns>
        public async Task DeleteRangeAsync(List<Guid> ids)
        {
            if (ids == null || !ids.Any())
            {
                return;
            }

            // 获取所有存在的折扣
            var discounts = await _orderDiscountRepository.Query()
                .Where(d => ids.Contains(d.Id))
                .ToListAsync();

            if (discounts.Any())
            {
                // 删除折扣
                await _orderDiscountRepository.DeleteRangeAsync(discounts);
            }
        }

        /// <summary>
        /// 计算订单总折扣金额
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>总折扣金额</returns>
        public async Task<decimal> CalculateTotalDiscountAsync(Guid orderId)
        {
            return await _orderDiscountRepository.GetTotalDiscountAmountAsync(orderId);
        }
    }
} 